package com.greenDao.activity.tool.button.event;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Spinner;

import com.greenDao.activity.R;
import com.greenDao.activity.tool.DatabaseUtils;
import com.greenDao.activity.tool.GuiUtils;
import com.greenDao.pojo.Event;
import com.greenDao.pojo.Movie;
import com.greenDao.pojo.PojoUtils;

public class ModifyUpdateEventButton implements OnClickListener {

	private final Activity activity;
	private final Spinner spinner;
	private final Long id;

	public ModifyUpdateEventButton(Activity activity, Long id, Spinner spinner) {
		this.activity = activity;
		this.spinner = spinner;
		this.id = id;
	}

	@Override
	public void onClick(View v) {

		String name = GuiUtils.getEditText(activity, R.id.nameEditModify);
		String time = GuiUtils.getEditText(activity, R.id.dateEditModify);
		String comment = GuiUtils.getEditText(activity, R.id.commentEditModify);

		if (name.isEmpty() || time.isEmpty() || spinner.getSelectedItem() == null) {
			GuiUtils.showAlertDialog(activity, "name, date and movie are obligatory");
			return;
		}

		if (!time.matches("\\d\\d-\\d\\d-\\d\\d\\d\\d--\\d\\d\\.\\d\\d")) {
			GuiUtils.showAlertDialog(activity, "bad date syntax, try again");
			return;
		}

		Date date = null;
		try {
			date = new SimpleDateFormat("dd-MM-yyyy--HH.mm", Locale.US).parse(time);
		} catch (ParseException e) {
			Log.e("AddEventButton onClick", "simple date format exception", e);
			GuiUtils.showAlertDialog(activity, "problem with parsing data");
			return;
		}
		String title = spinner.getSelectedItem().toString().split("-")[2];
		Movie movie = DatabaseUtils.findMoviesByTitle(title).get(0);

		Event change = PojoUtils.createEvent(name, movie, date, comment);
		DatabaseUtils.updateEventById(id, change);

		activity.finish();
	}
}
